<?php

namespace app\ttlock\controller;

use support\Request;
use think\facade\Db;
class IndexController
{
    protected $noNeedLogin = ['gettongtongtoken','openLock','closeLock','queryOpenState'];
    public function index(Request $request)
    {
        // $url = 'https://cnapi.ttlock.com/oauth2/token';
        // $data['clientId'] = 'e0591ebd2d974738bf0750b50a13a84a';
        // // $data['clientId'] = $clientId;
        // $data['clientSecret'] = '07ebafd493ad9ac04990d7762a98d9dc';
        // // $data['clientSecret'] = $clientSecret;
        // $data['username'] = '+8618652179779';
        // // $data['username'] = $username;
        // $data['password'] = md5('a6545279');
        // // $data['password'] = md5($password);
        // $res = $this->curl_post($url,$data);
        // return json($res);
    }

    //通通锁获取token
    public function gettongtongtoken($user_id,$clientId,$clientSecret,$username,$password){
        $token = Db::name('ttlock_token')->where(['user_id'=>$user_id])->find();
        if($token){
            if($token['expiretime']<=time()+24*60*60){
                //刷新token
                $url = 'https://cnapi.ttlock.com/oauth2/token';
                $data['clientId'] = $clientId;
                $data['clientSecret'] = $clientSecret;
                $data['grant_type'] = 'refresh_token';
                $data['refresh_token'] = $token['refresh_token'];
                $res = $this->curl_post($url,$data);
                if(isset($res['errcode'])){
                    return ['code'=>0,'msg'=>$res['description'],'data'=>[]];
                }else{
                    $ins['user_id'] = $user_id;
                    $ins['access_token'] = $res['access_token'];
                    $ins['refresh_token'] = $res['refresh_token'];
                    $ins['expiretime'] = time()+$res['expires_in'];
                    Db::name('ttlock_token')->where(['id'=>$token['id']])->update($ins);
                    return ['code'=>1,'msg'=>'ok','data'=>$res['access_token']];
                }
            }else{
                return ['code'=>1,'msg'=>'ok','data'=>$token['access_token']];
            }
        }else{
            $url = 'https://cnapi.ttlock.com/oauth2/token';
            $data['clientId'] = $clientId;
            $data['clientSecret'] = $clientSecret;
            $data['username'] = $username;
            $data['password'] = md5($password);
            $res = $this->curl_post($url,$data);
            if(isset($res['errcode'])){
                return ['code'=>0,'msg'=>$res['description'],'data'=>[]];
            }else{
                $ins['user_id'] = $user_id;
                $ins['access_token'] = $res['access_token'];
                $ins['refresh_token'] = $res['refresh_token'];
                $ins['expiretime'] = time()+$res['expires_in'];
                Db::name('ttlock_token')->insert($ins);
                return ['code'=>1,'msg'=>'ok','data'=>$res['access_token']];
            }

        }
        
    }
    //开启通通锁 lockId锁的id
    public function openLock(Request $request){
        $user_id = 1;
        // $lockId = '15626827';
        $lockId = $request->post('lockId','');
        if(!$lockId){
            return json(['code'=>0,'msg'=>'缺失参数lockId']);
        }
        $clientId = $request->post('clientId','');
        if(!$clientId){
            return json(['code'=>0,'msg'=>'缺失参数clientId']);
        }
        $clientSecret = $request->post('clientSecret','');
        if(!$clientSecret){
            return json(['code'=>0,'msg'=>'缺失参数clientSecret']);
        }
        $username = $request->post('username','');
        if(!$username){
            return json(['code'=>0,'msg'=>'缺失参数username']);
        }
        $password = $request->post('password','');
        if(!$password){
            return json(['code'=>0,'msg'=>'缺失参数password']);
        }
        $token = $this->gettongtongtoken($user_id,$clientId,$clientSecret,$username,$password);
        if($token['code']==0){
            return json(['code'=>0,'msg'=>$token['msg']]);
        }
        $accessToken = $token['data'];
        $url = 'https://cnapi.ttlock.com/v3/lock/unlock';
        $data['clientId'] = $clientId;
        $data['accessToken'] = $accessToken;
        $data['lockId'] = $lockId;
        $data['date'] = time()*1000;
        $res = $this->curl_post($url,$data);
        return json($res);
    }
    //关闭通通锁 lockId锁的id
    public function closeLock(Request $request){
        $user_id = 1;
        // $lockId = '15626827';
        $lockId = $request->post('lockId','');
        if(!$lockId){
            return json(['code'=>0,'msg'=>'缺失参数lockId']);
        }
        $clientId = $request->post('clientId','');
        if(!$clientId){
            return json(['code'=>0,'msg'=>'缺失参数clientId']);
        }
        $clientSecret = $request->post('clientSecret','');
        if(!$clientSecret){
            return json(['code'=>0,'msg'=>'缺失参数clientSecret']);
        }
        $username = $request->post('username','');
        if(!$username){
            return json(['code'=>0,'msg'=>'缺失参数username']);
        }
        $password = $request->post('password','');
        if(!$password){
            return json(['code'=>0,'msg'=>'缺失参数password']);
        }
        $token = $this->gettongtongtoken($user_id,$clientId,$clientSecret,$username,$password);
        if($token['code']==0){
            return json(['code'=>0,'msg'=>$token['msg']]);
        }
        $accessToken = $token['data'];
        $url = 'https://cnapi.ttlock.com/v3/lock/lock';
        $data['clientId'] = $clientId;
        $data['accessToken'] = $accessToken;
        $data['lockId'] = $lockId;
        $data['date'] = time()*1000;
        $res = $this->curl_post($url,$data);
        return json($res);
    }
    //获取锁的开关状态
    public function queryOpenState(Request $request){
        $user_id = 1;
        // $lockId = '15626827';
        $lockId = $request->post('lockId','');
        if(!$lockId){
            return json(['code'=>0,'msg'=>'缺失参数lockId']);
        }
        $clientId = $request->post('clientId','');
        if(!$clientId){
            return json(['code'=>0,'msg'=>'缺失参数clientId']);
        }
        $clientSecret = $request->post('clientSecret','');
        if(!$clientSecret){
            return json(['code'=>0,'msg'=>'缺失参数clientSecret']);
        }
        $username = $request->post('username','');
        if(!$username){
            return json(['code'=>0,'msg'=>'缺失参数username']);
        }
        $password = $request->post('password','');
        if(!$password){
            return json(['code'=>0,'msg'=>'缺失参数password']);
        }
        $token = $this->gettongtongtoken($user_id,$clientId,$clientSecret,$username,$password);
        if($token['code']==0){
            return json(['code'=>0,'msg'=>$token['msg']]);
        }
        $accessToken = $token['data'];
        $url = 'https://cnapi.ttlock.com/v3/lock/queryOpenState';
        $data['clientId'] = $clientId;
        $data['accessToken'] = $accessToken;
        $data['lockId'] = $lockId;
        $data['date'] = time()*1000;
        $res = $this->curl_post($url,$data);
        return json($res);
    }
    //curl请求
    private function curl_post(string $url, array $params) {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => http_build_query($params),
            CURLOPT_HTTPHEADER => [
                // 'content-type: application/json',
                'content-type: application/x-www-form-urlencoded'
            ],
        ]);
        $result = curl_exec($ch);
        $err = curl_errno($ch);
        curl_close($ch);
        if ($err) {
            throw new RuntimeException('RequestApi Error：'.$err);
        }
        return json_decode($result,true);
    }
}
